<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="标题" v-model="listQuery.title">
      </el-input>
      <el-select clearable style="width: 90px" class="filter-item" v-model="listQuery.importance" placeholder="重要性">
        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item">
        </el-option>
      </el-select>

      <el-select clearable class="filter-item" style="width: 130px" v-model="listQuery.type" placeholder="类型">
        <el-option v-for="item in  calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key">
        </el-option>
      </el-select>

      <el-select @change='handleFilter' style="width: 120px" class="filter-item" v-model="listQuery.sort" placeholder="排序">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key">
        </el-option>
      </el-select>

      <el-button class="filter-item" type="primary" v-waves icon="search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="edit">添加</el-button>
      <el-button class="filter-item" type="primary" icon="document" @click="handleDownload">导出</el-button>
      <el-checkbox class="filter-item" @change='tableKey=tableKey+1' v-model="showAuditor">显示审核人</el-checkbox>
    </div>

    <el-table :key='tableKey' :data="list" v-loading.body="listLoading" border fit highlight-current-row style="width: 100%">
      <el-table-column align="center" label="ID" width="65">
        <template scope="scope">
          <span>{{scope.row.id}}</span>
        </template>
      </el-table-column>

      <el-table-column width="180px" align="center" label="创建时间">
        <template scope="scope">
          <span>{{Date.parse(scope.row.createTime) | parseTime('{y}-{m}-{d} {h}:{i}')}}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="300px" label="标题">
        <template scope="scope">
          <span class="link-type" @click="handleUpdate(scope.row)">{{scope.row.title}}</span>
          <el-tag>{{scope.row.appName }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column min-width="300px" label="留言配置">
        <template scope="scope">
          <span class="link-type" @click="handleUpdate(scope.row)">{{scope.row.title}}</span>
          <el-tag>{{scope.row.appName }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column min-width="300px" label="管理员列表">
        <template scope="scope">
          <span class="link-type" @click="handleUpdate(scope.row)">{{scope.row.title}}</span>
          <el-tag v-for="item in scope.row.adminList" :key="item">{{item }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="250">
        <template scope="scope">
          <el-button v-if="scope.row.status!='published'" size="small" type="success" @click="handleModifyStatus(scope.row,'published')">查看列表 </el-button>
          <el-button v-if="scope.row.status!='published'" size="small" type="success" @click="handleModifyStatus(scope.row,'published')">停用 </el-button>

          <el-button v-if="scope.row.status!='deleted'" size="small" type="danger" @click="handleModifyStatus(scope.row,'deleted')">删除 </el-button>
        </template>
      </el-table-column>

    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :model="tempMessage" class="small-space" label-position="left" label-width="170px" :rules="tempRules" ref="addMessage">
        <el-form-item label="应用名称" prop="appName">
          <el-input v-model="tempMessage.appName" placeholder="请输入留言应用名称"></el-input>
        </el-form-item>
        <el-form-item label="应用适配地址">
          <el-input v-model="tempMessage.appUrl" placeholder="多个url用,分割"></el-input>
        </el-form-item>
        <el-form-item label="需要登录">
          <el-switch v-model="tempMessage.isNeedLogin" on-text="" off-text="">
          </el-switch>
        </el-form-item>
        <el-form-item label="需要审核">
          <el-switch v-model="tempMessage.isNeedCheck" on-text="" off-text="">
          </el-switch>
        </el-form-item>
        <el-form-item label="授权">
          <el-transfer class="transfer-auth" filterable :filter-method="filterMethod" filter-placeholder="请输入用户姓名" v-model="tempMessage.adminList" :data="cities">
          </el-transfer>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="create">确 定</el-button>
        <el-button v-else type="primary" @click="update">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="阅读数统计" :visible.sync="dialogPvVisible" size="small">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="渠道"> </el-table-column>
        <el-table-column prop="pv" label="pv"> </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<style scoped lang="scss">
.el-form-item {
  line-height: 2;
}
</style>
<style lang="scss">
.transfer-auth {
  height: auto;
  .el-transfer-panel__body {
    height: 290px;
  }
}
</style>
<script>
import { getMessageList, addMessage } from 'api/message';
import { getUserList } from 'api/user';
import { parseTime } from 'utils';

const calendarTypeOptions = [
  { key: 'CN', display_name: '中国' },
  { key: 'US', display_name: '美国' },
  { key: 'JP', display_name: '日本' },
  { key: 'EU', display_name: '欧元区' }
];

// arr to obj
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name;
  return acc
}, {});

export default {
  name: 'message_control',
  data() {
    return {
      list: null,
      total: null,
      temp: {},
      tempMessage: {
        isNeedLogin: true,
        isNeedCheck: true,
        appUrl: '',
        appName: '',
        adminList: []
      },
      tempRules: {
        appName: [
          { required: true, message: '请输入留言应用名称', trigger: 'blur' },
          { min: 5, max: 20, message: '长度在 5 到 20 个字符', trigger: 'blur' }
        ]
      },
      listLoading: true,
      userList: [],
      listQuery: {
        page: 0,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: '按ID升序列', key: '+id' }, { label: '按ID降序', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      dialogPvVisible: false,
      pvData: [],
      showAuditor: false,
      tableKey: 0

    }
  },
  computed: {
    cities: function() {
      const data = [];
      const cities = this.userList.map(item => item.username);
      const pinyin = this.userList.map(item => item.username);

      cities.forEach((city, index) => {
        data.push({
          label: city,
          key: index,
          pinyin: city
        });
      });
      console.log(data, 1);
      return data;
    }
  },
  created() {
    this.getMessageList();
    this.getUserList();
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      };
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  methods: {
    filterMethod(query, item) {
      console.log(item, query)
      return item.pinyin.indexOf(query) > -1;
    },
    getMessageList() {
      this.listLoading = true;
      getMessageList(this.listQuery).then(response => {
        // console.log(response, 123)
        let jsonData = response.data;

        console.log(jsonData, '获取留言列表')
        this.list = jsonData.data;
        this.total = jsonData.data.length;
        this.listLoading = false;
      })
    },
    getUserList() {
      this.listLoading = true;
      getUserList().then(response => {
        let jsonData = response.data;
        console.log(jsonData, '获取用户列表')
        this.userList = jsonData.data;
      })
    },
    handleFilter() {
      this.getMessageList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    timeFilter(time) {
      if (!time[0]) {
        this.listQuery.start = undefined;
        this.listQuery.end = undefined;
        return;
      }
      this.listQuery.start = parseInt(+time[0] / 1000);
      this.listQuery.end = parseInt((+time[1] + 3600 * 1000 * 24) / 1000);
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      });
      row.status = status;
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = 'create';
      this.dialogFormVisible = true;
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row);
      this.dialogStatus = 'update';
      this.dialogFormVisible = true;
    },
    handleDelete(row) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      });
      const index = this.list.indexOf(row);
      this.list.splice(index, 1);
    },
    create() {

      this.$refs['addMessage'].validate((valid) => {
        if (valid) {
          let message = this.tempMessage;
          message.adminList = message.adminList.map(item => this.userList[item]);
          addMessage(message).then(response => {

            let jsonData = response.data;
            console.log(jsonData, '添加留言返回')
          })
          console.log(message, '213123', this.userList[0])


        } else {
          this.$notify({
            title: '失败',
            message: '有字段未正确填写',
            type: 'error',
            duration: 2000
          });
          return false;
        }
      });

    },
    update() {

      this.dialogFormVisible = false;
      this.$notify({
        title: '成功',
        message: '更新成功',
        type: 'success',
        duration: 2000
      });
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 0,
        remark: '',
        timestamp: 0,
        title: '',
        status: 'published',
        type: ''
      };
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData;
        this.dialogPvVisible = true;
      })
    },
    handleDownload() {
      require.ensure([], () => {
        const { export_json_to_excel } = require('vendor/Export2Excel');
        const tHeader = ['时间', '地区', '类型', '标题', '重要性'];
        const filterVal = ['timestamp', 'province', 'type', 'title', 'importance'];
        const data = this.formatJson(filterVal, this.list);
        export_json_to_excel(tHeader, data, 'table数据');
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
